<!--
 * @Author: your name
 * @Date: 2021-08-23 20:01:50
 * @LastEditTime: 2021-08-29 19:11:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue电商管理平台\vue-e-commerce\src\components\goods\Cate.vue
-->


<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :data="catelist"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        class="treeTable"
      >
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error" v-else></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditCateDialog(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类 的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose"
    >
      <el-form
        :model="addCateForm"
        :rules="rules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
          ></el-cascader> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类 的对话框 -->
    <el-dialog title="提示" :visible.sync="editCateDialogVisible" width="50%">
      <el-form
        :model="editCateForm"
        :rules="rules"
        ref="editFormRef"
        label-width="100px"
        @close="editCateDialogClose"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catelist: [],
      //获取商品分类的请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //数据总量
      total: 0,
      //table 的 列
      columns: [
        { label: "分类名称", prop: "cat_name" },
        { label: "排序", type: "template", template: "isok" },
        { label: "是否有效", type: "template", template: "order" },
        { label: "操作", type: "template", template: "opt", width: "180px" },
      ],
      // 对话框 显示/隐藏
      addCateDialogVisible: false,
      editCateDialogVisible: false,
      //添加分类的表单数据
      addCateForm: {
        cat_pid: 0,
        cat_name: "",
        cat_level: 0,
      },
      //验证规则
      rules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //父级分类
      parentCateList: [],
      //cascader 的配置项
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      //cascader 选中的父级分类的 cat_id
      selectedKeys: [],
      //编辑分类的表单数据
      editCateForm: {
        cat_name: "",
        cat_id: 0,
      },
    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$axios.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("商品分类请求失败");
      }
      this.catelist = res.data.result;
      this.total = res.data.total;
    },
    // 监听 pagesize 的改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    //监听 pagenum 的改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    //监听 添加分类 对话框 打开
    showAddCateDialog() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //获取父级分类
    async getParentCateList() {
      const { data: res } = await this.$axios.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类失败");
      }
      this.parentCateList = res.data;
    },
    //监听 cascader 级联选择器 值改变
    parentCateChange() {
      const len = this.selectedKeys.length;
      if (len > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[len - 1];
        this.addCateForm.cat_level = len;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    //添加分类
    addCate() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$axios.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品分类失败");
        }
        this.$message.success("添加添加商品分类成功");
        this.getCateList();
        this.addCateDialogVisible = false;
      });
    },
    //监听 添加分类 对话框 关闭
    addCateDialogClose() {
      this.$refs.addFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    // 删除分类
    removeCate(id) {
      this.$confirm("是否删除该分类?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$axios.delete("categories/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getCateList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //监听 编辑分类 对话框 打开
    async showEditCateDialog(id) {
      const { data: res } = await this.$axios.get("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类失败");
      }
      this.editCateForm.cat_name = res.data.cat_name;
      this.editCateForm.cat_id = id;
      this.editCateDialogVisible = true;
    },
    //编辑分类
    editCate() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$axios.put(
          "categories/" + this.editCateForm.cat_id,
          { cat_name: this.editCateForm.cat_name }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("编辑商品分类失败");
        }
        this.$message.success("编辑商品分类成功");
        this.getCateList();
        this.editCateDialogVisible = false;
      });
    },
    //编辑 添加分类 对话框 关闭
    editCateDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style  scoped>
.el-icon-success {
  color: lightgreen;
}
.el-icon-error {
  color: red;
}
.treeTable {
  margin-top: 15px;
}
</style>